const express = require("express");
const fs = require("fs");
const path = require("path");
const OSS = require("ali-oss");
const multer = require("multer");
const { Client } = require("./main");
const { filter } = require("./fifter");
const fetch = require("node-fetch");
const cors = require("cors");
const app = express();

app.use(cors());
app.use(express.json());

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = "uploads/";
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir);
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(
      null,
      file.fieldname + "-" + uniqueSuffix + path.extname(file.originalname)
    );
  },
});

const upload = multer({
  storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 限制10MB
  },
});

// 配置 OSS 客户端
const client = new OSS({
  region: "oss-cn-beijing", // 您 Bucket 所在的地域
  accessKeyId: "LTAI5t7EX6ki2crvDwzAhcEn",
  accessKeySecret: "PvsHZXCAJLyn0NMOvNurICrjOGFCEk",
  bucket: "ceshigpx",
});

/**
 * 上传文件到OSS
 * @param {string} objectName OSS存储的文件名
 * @param {string} filePath 本地文件路径
 */
async function uploadFile(objectName, filePath) {
  try {
    const result = await client.put(objectName, filePath);
    return result;
  } catch (err) {
    throw err;
  }
}

async function fetchGet(url, headers = {}) {
  try {
    const response = await fetch(url, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        ...headers, // 合并自定义请求头
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json(); // 直接返回解析后的JSON数据
  } catch (error) {
    console.error("Fetch GET请求失败:", error);
    throw error; // 重新抛出错误，方便调用者处理
  }
}

app.post("/api/filter", async (req, res) => {
  try {
    // 从请求体中获取数组
    const itemsArray = req.body.imgList;

    const imgUrl = await filter(itemsArray);
    console.log("imgUrl", imgUrl);

    const content = await Client.main(imgUrl);
    const res1 = await startToJson(content);
    console.log("res1", res1);
    // 返回响应
    res.json({
      status: 1,
      imgUrl: imgUrl,
      result: res1,
    });
  } catch (error) {
    console.log("error", error);
    res.status(500).json({ error: "服务器内部错误" });
  }
});

const system_prompt = `你是一个专业的数据转换助手，请将表格数据转换为JSON数组。要求：
1. 输入是表格数据，第一行为表头
2. 输出必须是纯JSON数组，格式如下：
[
  {
    "size": "M",
    "length": 69,
    "bust": 116,
    "shoulder": 55,
    "sleeve": 23
  }
]
3. 字段映射：
   - "尺寸" → "size"
   - "衣长" → "length"
   - "胸围" → "bust"
   - "肩宽" → "shoulder"
   - "袖长" → "sleeve"
4. 忽略空行或无效行`;

const startToJson = async (val) => {
  const messages = [
    { role: "system", content: system_prompt },
    { role: "user", content: val },
  ];

  const apiKey = "sk-2be49d70cbd248508c5bd75549976633"; // 替换为你的API密钥
  const url = "https://api.deepseek.com/chat/completions";
  const requestBody = {
    model: "deepseek-chat",
    stream: false,
    messages: messages,
    temperature: 0.3, // 添加参数减少随机性
  };

  // requestBody.response_format = {
  //   type: "json_array",
  // };

  const data = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(requestBody),
  }).then(async (response) => {
    if (!response.ok) {
      const errorData = await response.json(); // 尝试获取详细的错误信息
      console.error("API Error Details:", errorData);
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  });

  const jsonData = data.choices[0].message.content;
  const cleanedJson = jsonData.replace(/```json|```/g, "").trim();
  return JSON.parse(cleanedJson);
};

app.listen(5000, () => {
  console.log("服务器运行在 http://localhost:5000");
});
